using DailyPoetryX.Services;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;

namespace DailyPoetryX.ViewModels {
    public class MainPageViewModel : ViewModelBase {
        /******** 构造函数 ********/

        private IPoetryStorage poetryStorage;
        private IFavoriteStorage favoriteStorage;
        private IRootNavigationService rootNavigationService;

        public MainPageViewModel(IPoetryStorage poetryStorage,
            IFavoriteStorage favoriteStorage,
            IRootNavigationService rootNavigationService) {
            this.poetryStorage = poetryStorage;
            this.favoriteStorage = favoriteStorage;
            this.rootNavigationService = rootNavigationService;
        }

        /******** 绑定属性 ********/

        /******** 绑定命令 ********/

        public RelayCommand PageAppearingCommand =>
            _pageAppearingCommand ?? (_pageAppearingCommand = new RelayCommand(
                async () => {
                    var run = false;

                    if (!pageLoaded) {
                        lock (pageLoadedLock) {
                            if (!pageLoaded) {
                                pageLoaded = true;
                                run = true;
                            }
                        }
                    }

                    if (!run) return;

                    if (!poetryStorage.Initialized() ||
                        !favoriteStorage.Initialized()) {
                        await rootNavigationService.NavigateToAsync(
                            RootNavigationServiceConstants.InitializationPage);
                        return;
                    }

                    await rootNavigationService.NavigateToAsync(
                        RootNavigationServiceConstants.TodayPage);
                }));

        private RelayCommand _pageAppearingCommand;

        /******** 私有变量 ********/

        private bool pageLoaded;
        private readonly object pageLoadedLock = new object();
    }
}